/* eslint-disable jsdoc/require-param-description */
'use strict';
const Service = require('egg').Service;
const { Op } = require('sequelize');
class CwRbacService extends Service {
  /**
   * check auth
   * @param  {String} name [auth type]
   * @param {number} uid 用户id
   * @return {Promise}      []
   */
  async check(name, uid) {
    if (!name || !uid) return false;
    const { cw } = this.ctx.helper;
    const map = {};
    map.include = [{
      model: this.ctx.model.CwRole,
    }];
    map.where = {};
    map.where.id = uid;
    map.where.state = true;
    const userInfo = await this.ctx.model.CwUser.findOne(map);
    if (userInfo) {
      if (userInfo.admin) return true;
      let ids = '';
      for (const v of userInfo.cw_roles) {
        console.log(v.menu_ids);
        ids += v.menu_ids;
      }
      const roleIds = cw._.uniq(cw._.split(ids, ',')).map(Number);
      const role = await this.ctx.model.CwMenu.findOne({ where: { path: { [Op.eq]: name }, id: { [Op.in]: roleIds } } });
      return !!role;
    }
    return false;
  }
  async getRoleIds(uid) {
    if (!uid) return [];
    const { cw } = this.ctx.helper;
    const map = {};
    map.include = [{
      model: this.ctx.model.CwRole,
    }];
    map.where = {};
    map.where.id = uid;
    const userInfo = await this.ctx.model.CwUser.findOne(map);
    if (userInfo.admin) return [];
    let ids = '';
    for (const v of userInfo.cw_roles) {
      console.log(v.menu_ids);
      ids += v.menu_ids;
    }
    return cw._.uniq(cw._.split(ids, ',')).map(Number);
  }
}
module.exports = CwRbacService;
